package com.makenv.web.portal;

import com.makenv.domain.Url;
import com.makenv.service.UrlService;
import com.makenv.util.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/index")
public class IndexController {

    @Autowired
    UrlService urlService;

    //从配置文件中读取的每次显示的行数
    private int row;

    /**
     * @Author : lilimin
     * @Description : 首页显示各种url
     * @Date : Created in 23:12 2017/11/26
     */

    @RequestMapping("/show")
    public String show(HttpServletRequest request) {
        forShow(request);
        return "front/index";
    }

    @RequestMapping("/jump")
    public String jump(@RequestParam int pageNum, HttpServletRequest request) {
        int pageSum = getPageSum();
        request.getSession().setAttribute("pageSum", pageSum);
        request.getSession().setAttribute("pageNum", pageNum);
        List<Url> urlList = urlService.showUrlList((pageNum - 1) * row, row);
        request.setAttribute("urlList", urlList);
        return "front/index";
    }


    public void forShow(HttpServletRequest request) {
        row = Config.getInt("showRow");
        List<Url> urlList = urlService.showUrlList(0, row);
        int pageSum = getPageSum();
        request.getSession().setAttribute("pageSum", pageSum);
        request.getSession().setAttribute("pageNum", 1);
        request.setAttribute("urlList", urlList);
    }

    public Integer getPageSum() {
        int pageSum;
        int totalUrl = urlService.getUrlsum();
        if (totalUrl % row == 0) {
            pageSum = totalUrl / row;
        } else {
            pageSum = totalUrl / row + 1;
        }
        return pageSum;
    }
}